package com.hskn.hss.module.common.controller;

import com.hskn.hss.config.Config;
import com.hskn.hss.core.utils.StringUtils;
import com.hskn.hss.module.common.to.CommonDownloadTO;
import com.hskn.hss.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用请求处理
 * 
 * @author shy
 */
@Api(tags = {"-common"}, description = "通用接口")
@RestController
@RequestMapping("/hss/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    /**
     * 通用下载请求
     * 
     * @param commonDownloadTO。fileName 文件名称
     * @param commonDownloadTO。delete 是否删除
     */
    @ApiOperation(value = "通用下载请求", notes = "通用下载请求")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @GetMapping("/download")
    public void fileDownload( CommonDownloadTO commonDownloadTO, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(commonDownloadTO.getFileName()))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", commonDownloadTO.getFileName()));
            }
            String realFileName =  commonDownloadTO.getFileName().substring( commonDownloadTO.getFileName().indexOf("_") + 1);
            String filePath = Config.getDownloadPath() +  commonDownloadTO.getFileName();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (commonDownloadTO.getDelete())
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
